/**
 * @file language.c
 * @brief language
 * @author JakeYang <add358@gmail.com>
 * @version 0.1
 * @date 2016-05-26
 */

#include "language.h"

#include <pthread.h>

#include <libxml/parser.h>
#include <libxml/tree.h>

#define LANGUAGE_DIR "./language"

static GHashTable *language = NULL;
static pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;

void _language_load(const gchar *buf, gsize len)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr curNode = NULL;

    xmlKeepBlanksDefault(0);
    doc = xmlParseMemory(buf, len);
    if (NULL == doc) {
        goto _language_end;
    }

    curNode = xmlDocGetRootElement(doc);
    if (NULL == curNode || xmlStrcmp(curNode->name, "Language")) {
        goto _language_end;
    }
    curNode = curNode->children;

    pthread_rwlock_wrlock(&rwlock);
    language = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
    for (; curNode; curNode = curNode->next) {
        g_hash_table_insert(language, xmlGetProp(curNode, "key"), xmlNodeGetContent(curNode));
    }
    pthread_rwlock_unlock(&rwlock);

_language_end:
    xmlFreeDoc(doc);
//    xmlCleanupParser();
}

void language_load(LanguageType type)
{
    gchar *buf = NULL;
    gsize len;
    gchar *file = LANGUAGE_DIR"/Chinese";
    if (ENGLISH == type) {
        language_unload();
        return;
    }

    if ( !g_file_get_contents(file, &buf, &len, NULL) ) {
        return;
    }

    language_unload();
    _language_load(buf, len);
}


void language_unload()
{
    pthread_rwlock_wrlock(&rwlock);
    if (language) {
        g_hash_table_destroy(language);
        language = NULL;
    }
    pthread_rwlock_unlock(&rwlock);
}

const gchar *language_get_text(const gchar *str)
{
    const gchar *txt = NULL;
    pthread_rwlock_rdlock(&rwlock);
    if (language) {
        txt = g_hash_table_lookup(language, str);
    }
    pthread_rwlock_unlock(&rwlock);
    if (txt) {
        return txt;
    }
    return str;
}
